package com.py.credit.controller;


import com.alibaba.fastjson.JSON;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.*;
import com.py.credit.service.UploadPublicService;
import com.py.credit.service.UploadService;
import com.py.credit.service.UploadXydService;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.SMUtils;
import com.py.credit.utils.SubmitConvXmlUtils;
import com.py.framework.core.annotation.IgnoreAuthority;

import com.py.framework.core.log.ExceptionLogger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.namespace.QName;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/uploadPublic")
public class UploadPublicController {
    protected int socketTimeout = 30000;// 请求超时时间
    protected int connectTimeout = 30000;// 传输超时时间
    protected String UploadPostUrl = "https://59.227.152.250:8443/creditdatas/ws/XzzfService?wsdl";
    protected String apiKey = "B9A7C23C0E394E86B90436740A491958";
    private final Logger log = LoggerFactory.getLogger(UploadPublicController.class);
    protected String namespace = "com.test.webservices";//命名空间

    @Autowired
    private UploadPublicService uploadPublicService;

    /**
     * 监督检查
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadJdjc.json")
    public RestServiceResult<Object>  uploadJdjc(int type) throws UnsupportedEncodingException {
    	RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadJdjc(type,namespace, UploadPostUrl,  "importJdjcXml");
        	result.setData(data);
			return result;
        } catch (Exception e) {
        	ExceptionLogger.error("UploadPublicController#uploadJdjc", "监督检查信息回传异常！ERROR：" + e.getMessage(), e);
        	result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("监督检查回传定时任务异常！");
			return result;
        }

    }

    /**
     * 行政强制
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzqz.json")
    public RestServiceResult<Object>  uploadXzqz(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzqz(type, namespace, UploadPostUrl, "importXzqzXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzqz", "行政强制信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政强制回传定时任务异常！");
            return result;
        }

    }

    /**
     * 行政征收
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzzs.json")
    public RestServiceResult<Object>  uploadXuploadXzzszqz(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzzs(type, namespace, UploadPostUrl, "importXzzsXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzzs", "行政征收信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政征收回传定时任务异常！");
            return result;
        }

    }

    /**
     * 行政给付
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzjf.json")
    public RestServiceResult<Object>  uploadXzjf(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzjf(type, namespace, UploadPostUrl, "importXzjfXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzjf", "行政给付信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政给付回传定时任务异常！");
            return result;
        }

    }

    /**
     * 行政奖励
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzjl.json")
    public RestServiceResult<Object>  uploadXzjl(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzjl(type, namespace, UploadPostUrl, "importXzjlXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzjl", "行政奖励信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政奖励回传定时任务异常！");
            return result;
        }

    }

    /**
     * 行政裁决
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzcj.json")
    public RestServiceResult<Object>  uploadXzcj(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzcj(type, namespace, UploadPostUrl, "importXzcjXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzcj", "行政裁决信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政裁决回传定时任务异常！");
            return result;
        }

    }

    /**
     * 行政确认
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadXzqr.json")
    public RestServiceResult<Object>  uploadXzqr(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadXzqr(type, namespace, UploadPostUrl, "importXzqrXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadXzqr", "行政确认信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("行政确认回传定时任务异常！");
            return result;
        }

    }

    /**
     * 其他行政管理
     * 0 法人 1 自然人
     */
    @IgnoreAuthority
    @RequestMapping(value = "/uploadQtxzgl.json")
    public RestServiceResult<Object>  uploadQtxzgl(int type) throws UnsupportedEncodingException {
        RestServiceResult<Object> result = new RestServiceResult<Object>();

        try {
            Object data = uploadPublicService.uploadQtxzgl(type, namespace, UploadPostUrl, "importQtxzzfxxXml");
            result.setData(data);
            return result;
        } catch (Exception e) {
            ExceptionLogger.error("UploadPublicController#uploadQtxzgl", "其他行政管理信息回传异常！ERROR：" + e.getMessage(), e);
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("其他行政管理回传定时任务异常！");
            return result;
        }

    }
    /**
     *
     * @param type 0 法人许可 1 自然人许可 2 法人处罚 3 自然人处罚  4 法人承诺书 5 自然人承诺书
     * @param namespace
     * @param postUrl
     * @param method
     * @return
     * @throws UnsupportedEncodingException
     */

    public String execute(int type,String namespace, String postUrl, String method) throws UnsupportedEncodingException {
        try {
            String tableName="";
            if(type==0){
                tableName="t_1000000010547_flvav2m67i";
//                List<EnterprisesEntity> list = upLoadXydService.getEnterprisesList();
//                List<List<EnterprisesEntity>> parList = ListUtils.partition(list, 1000);
                String xzxkXmlValue = "";
                System.out.println("上报数据转换成xml" + xzxkXmlValue);
                log.debug("行政许可转XML内容：{}", xzxkXmlValue);
                String respXzxkValue = doPostSoap1_1(postUrl, xzxkXmlValue,apiKey, method);

                log.info("返回行政许可上报结果信息：{}", respXzxkValue);
                System.out.println("返回行政许可上报结果信息：{}" + respXzxkValue);

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传数据失败:", e.getMessage());
        }
        return null;
    }

    /**
     * 使用SOAP1.1发送消息
     *
     * @param postUrl
     * @param soapXml
     * @param soapAction
     * @return
     */
    public String doPostSoap1_1(String postUrl, String soapXml, String apiKey,
                                String soapAction) throws UnsupportedEncodingException {

    	javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(

    			new javax.net.ssl.HostnameVerifier(){

    			public boolean verify(String hostname,

    			javax.net.ssl.SSLSession sslSession) {
    			return true;


    			}

    			});

    			System.clearProperty("javax.net.ssl.trustStore");

    			System.clearProperty("javax.net.ssl.trustStorePassword");

    			try {

    			//这里需要注意的是证书路径如果有空格，上面getPath()会把空格转码为%20F，需要转一次码，其他特殊字符也需注意
    		    	  System.setProperty("javax.net.ssl.trustStore", "C:\\cacerts");
    		    	  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    		    	  System.setProperty("org.jboss.security.ignoreHttpsHost", "true");
    			} catch (Exception e) {

    			e.printStackTrace();

    			}
    	
        try {
            Properties props = System.getProperties();
            props.setProperty("org.apache.cxf.stax.allowInsecureParser", "1");
            props.setProperty("UseSunHttpHandler", "true");
            props.setProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");;
            String nameSpace = "http://dal.rjcloud.dal";
            TLSClientParameters tlsParams = new TLSClientParameters();
			tlsParams.setDisableCNCheck(true);
			
            JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
            Client client = clientFactory.createClient(postUrl);
            HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
			httpConduit.setTlsClientParameters(tlsParams);
            System.out.println("请求地址:"+postUrl);
            System.out.println("请求方法:"+soapAction);
            Object[] obj = client.invoke(soapAction, new Object[]{apiKey,soapXml});
            System.out.println("请求结果:");
            System.out.println(String.valueOf(obj[0]));
            return String.valueOf(obj[0]);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    return "";
    }



    public  String getImgStrBase64(String imagePath) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        if(StringUtils.isNotBlank(imagePath)){
            InputStream in = null;
            byte[] data = null;
            // 读取图片字节数组
            try {
                in = new FileInputStream(imagePath);
                data = new byte[in.available()];
                in.read(data);
                in.close();
            } catch ( Exception e) {
                e.printStackTrace();
            }
            return Base64.encodeBase64String(data);
        }
        return "";

    }

    /**
     *
     * @param promiseList
     * @return
     */
    public List<FrPromiseBookBean> convert264(  List<FrPromiseBookBean> promiseList){
        for (FrPromiseBookBean promise:promiseList){
            promise.setPath_byte64(getImgStrBase64(promise.getPath_byte64()));
        }
        return promiseList;
    }
    /**
     *
     * @param promiseList
     * @return
     */
    public List<ZrrPromiseBookBean> convertZRR264(  List<ZrrPromiseBookBean> promiseList){
        for (ZrrPromiseBookBean promise:promiseList){
            promise.setPath_byte64(getImgStrBase64(promise.getPath_byte64()));
        }
        return promiseList;
    }
    public static Object[] invokeRemoteMethod(String url, String operation, Object[] parameters){
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!url.endsWith("wsdl")) {
            url += "?wsdl";
        }
        org.apache.cxf.endpoint.Client client = dcf.createClient(url);
        //处理webService接口和实现类namespace不同的情况，CXF动态客户端在处理此问题时，会报No operation was found with the name的异常
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(),operation);
        BindingInfo bindingInfo= endpoint.getEndpointInfo().getBinding();
        if(bindingInfo.getOperation(opName) == null){
            for(BindingOperationInfo operationInfo : bindingInfo.getOperations()){
                if(operation.equals(operationInfo.getName().getLocalPart())){
                    opName = operationInfo.getName();
                    break;
                }
            }
        }
        Object[] res = null;
        try {
            res = client.invoke(opName, parameters);
        } catch (Exception e) {
           System.out.println(e.getMessage());
        }
        return res;
    }
    public static void main(String[] args) throws Exception {
        String xzxkXmlValue = "";
        String postUrl = "http://222.143.254.175:8080/xyd/ws/XyrDataInterfaceService?wsdl";
        String soapAction = "getPublicKey";
        String apiKey = "72C136A8A67D4FC2A82797FE1952C5B9";

        JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = clientFactory.createClient(postUrl);
        System.out.println("请求地址:"+postUrl);
        System.out.println("请求方法:"+soapAction);
        //策略
        HTTPConduit http = (HTTPConduit)client.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        //连接超时(1分钟)
        httpClientPolicy.setConnectionTimeout(1 * 60000);
        httpClientPolicy.setAllowChunking(false);
        //响应超时(1分钟)
        httpClientPolicy.setReceiveTimeout(1 * 60000);
        http.setClient(httpClientPolicy);
      try {
    	  Object[] obj = client.invoke(soapAction, new Object[]{"72C136A8A67D4FC2A82797FE1952C5B9",""});
    	  System.out.println(String.valueOf(obj[0]));
      }catch (Exception e) {
    	  System.out.println(e);
		// TODO: handle exception
	}
        System.out.println("请求结果:");



    }
}
